package com.test.singlelon;

public class SingletonDemo {

    private static SingletonDemo instance = null;

    private SingletonDemo(){
        System.out.println(Thread.currentThread().getName()+"\t 我是构造方法");
    }

    public static synchronized SingletonDemo getInstance(){
        if(instance == null){
            instance = new SingletonDemo();
        }
        return instance;
    }

    public static void main(String[] args) {
        //单线程下
//        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()); //true
//        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()); //true

        //多线程下 会有问题，可以在getInstance 上添加synchronized，但是会导致整个方法加锁
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                SingletonDemo.getInstance();
            },String.valueOf(i)).start();
        }
    }
}
